<template>
  <el-dialog
    top="30px"
    width="600px"
    class="dialog-sm"
    append-to-body
    :before-close="handleClose"
    :close-on-click-modal="false"
    title="抵押主体"
    :visible.sync="visible"
  >
    <el-form
      :model="model"
      label-position="left"
      :rules="rules"
      ref="form"
      label-width="120px"
      v-loading="loading"
    >
      <el-form-item label="主体类型" prop="com_person_type">
        <c-select
          class="form-control-ml"
          v-model="model.com_person_type"
          placeholder="主体类型"
          :options="enumEntityType"
        ></c-select>
      </el-form-item>
      <el-form-item
        :label="
          isCommon
            ? '营业执照OCR识别(请上传清晰的图片，以确保识别准确性，非必填)'
            : '身份证头像页OCR识别(请上传清晰的图片，以确保识别准确性，非必填)'
        "
      >
        <upload-oss
          single-image
          :dir="dir"
          ref="uploadRegister"
          accept="image/*"
          :fileName="0"
          :file-list="registerList"
          :on-change="registerChange"
        ></upload-oss>
      </el-form-item>

      <el-form-item label="主体名称" prop="com_person_name">
        <el-input
          class="form-control-ml"
          v-model="model.com_person_name"
          placeholder="主体名称"
        ></el-input>
      </el-form-item>

      <el-form-item label="法人姓名" prop="com_person_corp" v-if="isCommon">
        <el-input
          class="form-control-ml"
          v-model="model.com_person_corp"
          placeholder="请输入法人姓名"
        ></el-input>
      </el-form-item>

      <el-form-item label="手机号(实名制手机号)" prop="com_person_phone">
        <el-input
          class="form-control-ml"
          v-model="model.com_person_phone"
          placeholder="请输入手机号"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="证件号"
        prop="cert_no"
        :rules="
          isCommon
            ? [
                { required: true, message: '请输入营业执照号', trigger: 'blur' },
                {
                  validator: registerNoValidator,
                  message: '请输入正确的营业执照号',
                  trigger: 'blur',
                },
              ]
            : [
                { required: true, message: '请输入身份证号码', trigger: 'blur' },
                {
                  validator: idCardValidator,
                  message: '请输入正确的身份证号码',
                  trigger: 'blur',
                },
              ]
        "
      >
        <el-input
          class="form-control-ml"
          v-model="model.cert_no"
          placeholder="请输入证件号"
        ></el-input>
      </el-form-item>

      <el-form-item label="联系地址" prop="com_person_address">
        <el-input
          class="form-control-ml"
          v-model="model.com_person_address"
          placeholder="请输入联系地址"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="btn-long" @click="handleBeforeSave">保存</el-button>
        <el-button class="btn-long" @click="handleClose">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { mobileValidator, idCardValidator, registerNoValidator } from '@/common/plugins/validator'
import { getIdCard, getOrgInfo } from '@/credit/views/city/program/ocr/index'
import { enumEntityType } from '@/credit/views/county/unionProvince/components/ContractGuardMortgage'
export default {
  components: {},
  props: {
    visible: Boolean,
    formData: {
      type: Object,
      default() {
        return {}
      },
    },
    attach: {
      type: Array,
      default() {
        return []
      },
    },
  },
  data() {
    return {
      enumEntityType,
      idCardValidator,
      registerNoValidator,
      loading: false,
      registerList: [],
      model: {
        file: null,
        url: '',
        cert_attachment: '',
        com_person_type: '2',
        com_person_name: '',
        com_person_corp: '',
        com_person_phone: '',
        cert_no: '',
        com_person_address: '',
        id: '', // 后端修改需要传id，为空时需删除字段
      },
      rules: {
        com_person_type: { required: true, message: '请选择主体类型', trigger: 'change' },
        com_person_name: { required: true, message: '请输入主体名称', trigger: 'blur' },
        com_person_corp: { required: true, message: '请输入法人姓名', trigger: 'blur' },
        com_person_phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: mobileValidator, message: '请输入正确的手机号码', trigger: 'blur' },
        ],
        com_person_address: { required: true, message: '请输入联系地址', trigger: 'blur' },
      },
      ocrFile: '',
    }
  },
  computed: {
    dir() {
      return `credit/newProjec/common/${this.model.cert_no}`
    },
    isCommon() {
      return +this.model.com_person_type === 1
    },
  },
  watch: {
    attach: {
      handler: function () {
        this.registerList = this.attach
      },
      immediate: true,
      deep: true,
    },
    formData: {
      handler: function () {
        Object.keys(this.model).forEach(key => {
          this.model[key] = this.formData[key] || ''
        })
        this.model.com_person_type = this.formData.com_person_type || '2'
      },
      immediate: true,
      deep: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    registerChange(file) {
      if (!file || !file.raw) {
        return
      }
      this.ocrFile = file.raw
      this.loading = true
      if (this.isCommon) {
        getOrgInfo(this.ocrFile)
          .then(res => {
            const data = res?.data ?? {}
            this.model.cert_no = data.reg_num || ''
            this.model.com_person_corp = data.person
            this.model.com_person_name = data.name
            this.model.com_person_address = data.address
          })
          .finally(() => {
            this.loading = false
          })
      } else {
        getIdCard(this.ocrFile, true)
          .then(res => {
            const data = res?.data ?? {}
            this.model.cert_no = data.num || ''
            this.model.com_person_name = data.name
            this.model.com_person_address = data.address
          })
          .finally(() => {
            this.loading = false
          })
      }
    },
    handleBeforeSave() {
      this.model.file = this.ocrFile
      this.model.url = this.ocrFile ? URL.createObjectURL(this.ocrFile) : ''
      if (!this.model.id) {
        delete this.model.id
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$emit('back', { ...this.model })
          this.handleClose()
        } else {
          this.$message.warning('填写的数据有误，请检查填写内容')
        }
      })
    },
    handleClose() {
      this.$emit('update:visible', false)
    },
    handleSuccess(res) {
      this.$emit('success', res)
    },
  },
}
</script>

<style lang="scss" scoped></style>
